package com.ygqh.baby.controller.admin;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.po.YgAlipayRefundRecord;
import com.ygqh.baby.po.YgRechargeMemberRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserMember;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.alipay.util.AlipayNotify;
import com.ygqh.baby.service.alipay.util.AlipaySubmit;
import com.ygqh.baby.utils.DateConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author admin
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private YgRechargeMemberRecordService ygRechargeMemberRecordService;
    @Autowired
    private YgUserMemberService ygUserMemberService;
    @Autowired
    private YgFrameCodeService ygFrameCodeService;
    @Autowired
    private YgAlipayRefundRecordService ygAlipayRefundRecordService;
    @Autowired
    private AlipaySubmit alipaySubmit;
    @Autowired
    private AlipayNotify alipayNotify;
    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Value("${alipay.refund.service}")
    private String refundService;
    @Value("${alipay.charset}")
    private String charset;
    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;
    @Value("${alipay.partner}")
    private String partner;
    @Value("${alipay.seller_id}")
    private String sellerId;
    @Value("${alipay.recharge.refund.notify_url}")
    private String refundFastpayNotifyUrl;

    @RequestMapping("searchUser")
    @ResponseBody
    public Map<String, Object> searchUser(String username, QueryInfo queryInfo,
                                          Date startDate, Date endDate, String nikename, String fromCode, UserType userType) throws ParseException {
        ResultSet<YgUser> resultSet = ygUserService.search(queryInfo, username, nikename, startDate, endDate, "", fromCode, null, userType);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("updateUserType")
    @ResponseBody
    public Message updateUserType(Long id, UserType userType, Integer level) {
//        logger.info("更新用户类型：id：{}，userType：{}，level:{}", new Object[]{id, userType, level});
        YgUser ygUser = new YgUser();
        ygUser.setId(id);
        ygUser.setUserType(userType);
        ygUser.setLevel(level);
        ygUser.setUpdateTime(new Date());
        ygUserService.updateUserInfo(ygUser);
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("updateDistributor")
    @ResponseBody
    public Message updateDistributor(@RequestParam Long id) {
        YgUser user = ygUserService.findById(id);
        UserType userType;

        if (UserType.Distributor.equals(user.getUserType())) {
            userType = UserType.Ordinary;
        } else if (user.getLevel() == 10 || user.getUserType().equals(UserType.UserAgent)) {
            return Message.error("女王、代理不能申请分销员");
        } else {
            userType = UserType.Distributor;
        }
        YgUser ygUser = new YgUser();
        ygUser.setId(id);
        ygUser.setUserType(userType);
        ygUser.setUpdateTime(new Date());
        ygUserService.updateUserInfo(ygUser);
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("updateUserLevel")
    @ResponseBody
    public Message updateUserLevel(Long id) {
        YgUser ygUser = new YgUser();
        ygUser.setId(id);
        ygUser.setLevel(1);
        ygUserService.updateUserInfo(ygUser);
        return SUCCESS_MESSAGE;
    }

    @RequestMapping(value = "sendCoupon")
    @ResponseBody
    public Message sendCoupon() {
        //获取总用户数
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        QueryInfo queryInfo = new QueryInfo(0, 100);

        List<YgUser> userList = ygUserService.selectUserByPage(queryInfo);
        StringBuffer buff = new StringBuffer();
        buff.append("清凉的、现货的、打折的！\n");
        buff.append("花仙子薄纱蛋糕短裤，清凉不起静电、嗲到飞起，原价99元拼团49元。\n");
        buff.append("一秒变网红的火烈鸟半裙，原价129元拼团69元。\n");
        buff.append("富士山下亲子连衣裙，女儿款129元，妈妈款99元，两个字：凉快！凉快！凉快！\n");
        buff.append("恋恋巴黎亲子连衣裙，女儿款、妈妈款均为99元，不足200元一起变成清凉小公举~天猫店新店开业大宴宾客！\n");

        buff.append("开业全场包邮、优惠力度max，错过不要来哭，摊手~\n");

        String link = "http://m.yiigoo.com/mall/index.html?sourceCode=ygwxf170724";
        String address = "你还有一张满299减129的券，再不去用还等什么呢！";
        String title = "夏季大爱爆品抢购";
        String time = "即日起";

        for (int i = 0; i < userList.size(); i++) {
            final int index = i;
            System.err.println("===============" + userList.get(index).getId() + "==========");
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    wxMpMessageService.sendServiceExpressMsg(buff.toString(), link, userList.get(index).getUserName(), title, userList.get(index).getOpenId(), address, time);
                }
            });
        }

        return SUCCESS_MESSAGE;
    }

    @RequestMapping("searchVipUser")
    @ResponseBody
    public Map<String, Object> searchVipUser(String q, QueryInfo queryInfo, String nickName) {
        ResultSet<YgUserMember> resultSet = ygUserMemberService.search(queryInfo, q, nickName);
        return resultSet.toDatatables(null);
    }

    @RequestMapping("searchCountVip")
    @ResponseBody
    public Map<String, Object> searchCountVip(QueryInfo queryInfo,
                                              @RequestParam(defaultValue = "RechargeMB") CodeType rechargeRecordType) {
        ResultSet<YgRechargeMemberRecord> resultSet =
                ygRechargeMemberRecordService.searchCountVip(queryInfo, rechargeRecordType);
        return resultSet.toDatatables(null);
    }

    @RequestMapping("getUserVipRecord")
    @ResponseBody
    public Map<String, Object> getUserVipRecord(String userName) {
        QueryInfo queryInfo = new QueryInfo();
        queryInfo.setEnd(20);
        ResultSet<YgRechargeMemberRecord> resultSet =
                ygRechargeMemberRecordService.search(queryInfo, userName, null, CodeType.RechargeMB);
        return resultSet.toDatatables(null);
    }

    /**
     * 女王购买记录
     *
     * @param userId
     * @return
     */
    @RequestMapping("getReChargeUserVip")
    @ResponseBody
    public Map<String, Object> getReChargeUserVip(Long userId,
                                                  @RequestParam(defaultValue = "RechargeMB") CodeType rechargeRecordType) {
        ResultSet<YgRechargeMemberRecord> resultSet = ygRechargeMemberRecordService.searchRecordByUserId(userId, rechargeRecordType);
        return resultSet.toDatatables(null);
    }

    /**
     * 退款女王充值记录(微信)
     *
     * @param id id
     * @param refundPrice refundPrice
     * @return
     */
    @RequestMapping("refundUserVipByWeixin")
    @ResponseBody
    public Message refundUserVipByWeixin(@RequestParam Long id, BigDecimal refundPrice) {
        YgRechargeMemberRecord rechargeMemberRecord = ygRechargeMemberRecordService.findById(id);
        try {
            validateRechargeMemberRecord(rechargeMemberRecord);
            if (PayType.Alipay.equals(rechargeMemberRecord.getPayType())) {
                return Message.error("该接口只支持微信支付退款", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Message.error(e.getMessage(), null);
        }
        String handler = getSession().getTrueName();
        if (refundPrice == null) {
            refundPrice = rechargeMemberRecord.getPaidPrice();
        }
        try {
            // 发起微信退款
            ygReturnOrderService.applyRefundNew(null, rechargeMemberRecord.getPayType(), rechargeMemberRecord.getAppType(),
                    rechargeMemberRecord.getPaymentCode().toString(), rechargeMemberRecord.getPaymentCode().toString(),
                    refundPrice, rechargeMemberRecord.getPaidPrice(), handler);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return Message.error(e.getMessage(), e);
        }
        ygRechargeMemberRecordService.refundSuccess(rechargeMemberRecord, handler, "实际退款金额" + refundPrice);
        return Message.success(null);
    }

    private void validateRechargeMemberRecord(YgRechargeMemberRecord rechargeMemberRecord) {
        Assert.isTrue(rechargeMemberRecord != null && rechargeMemberRecord.getPaidPrice().equals(rechargeMemberRecord.getMemberPrice()),
                "无效充值记录");
    }

    /**
     * 退款女王充值记录(支付宝退款发起)
     *
     * @param id
     * @return
     */
    @RequestMapping("refundUserVipByAlipay")
    @ResponseBody
    public Message refundUserVipByAlipay(@RequestParam Long id, BigDecimal refundPrice) {
        YgRechargeMemberRecord rechargeMemberRecord = ygRechargeMemberRecordService.findById(id);
        try {
            validateRechargeMemberRecord(rechargeMemberRecord);
            if (!PayType.Alipay.equals(rechargeMemberRecord.getPayType())) {
                return Message.error("该接口只支持支付宝支付退款", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Message.error(e.getMessage(), null);
        }
        if (refundPrice == null) {
            refundPrice = rechargeMemberRecord.getPaidPrice();
        }
        String batchNo = ygFrameCodeService.getFrameCode(CodeType.BatchNo, new Date(), "yyyyMMdd", 6);
        // 保存支付宝退款记录
        YgAlipayRefundRecord record = new YgAlipayRefundRecord(batchNo, 1, rechargeMemberRecord.getTransactionId(), id,
                rechargeMemberRecord.getPaymentCode().toString(), refundPrice, rechargeMemberRecord.getPaidPrice(), "女王退款",
                getSession().getTrueName());
        ygAlipayRefundRecordService.save(record);

        // 把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<>(9);
        sParaTemp.put("service", refundService);
        sParaTemp.put("partner", partner);
        sParaTemp.put("_input_charset", charset);
        sParaTemp.put("notify_url", refundFastpayNotifyUrl);
        sParaTemp.put("seller_user_id", sellerId);
        sParaTemp.put("refund_date", DateConvertUtils.formatDateTime(new Date()));
        sParaTemp.put("batch_no", batchNo);
        sParaTemp.put("batch_num", "1");
        sParaTemp.put("detail_data", rechargeMemberRecord.getTransactionId() + "^" + refundPrice + "^" + "女王退款");
        sParaTemp = alipaySubmit.buildRequestPara(sParaTemp);

        // 建立请求
        String buildRequest = alipaySubmit.buildRequest(sParaTemp, "get", "确认");
        return Message.success("<html><body>" + buildRequest + "</body></html>");
    }

    /**
     * 退款女王充值记录(支付宝退款成功通知)
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "refundFastpayNotifyUrl")
    public void refundFastpayNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> params = alipayNotify.getAlipayNotifyParam(request);
        // 批次号
        String batchNo = new String(request.getParameter("batch_no").getBytes("ISO-8859-1"), "UTF-8");
        // 批量退款数据中的详细信息
        String resultDetails = new String(request.getParameter("result_details").getBytes("ISO-8859-1"), "UTF-8");
        if (alipayNotify.verify(params)) {
            // 验证成功
            ygAlipayRefundRecordService.refundSuccess(batchNo, resultDetails, args -> {
                YgRechargeMemberRecord rechargeMemberRecord = ygRechargeMemberRecordService.findById(Long.valueOf(args[0].toString()));
                ygRechargeMemberRecordService.refundSuccess(rechargeMemberRecord, args[1].toString(), "实际退款金额");
            });
            response.getWriter().print("success");
        } else {
            // 验证失败
            response.getWriter().print("fail");
        }
    }

}
